
//引入msql
const mysql = require('mysql');
//拿到数据库配置信息
const mysqlConfig = require('./mysqlConfig').database;

//创建数据库连接池
const pool = mysql.createPool({
  connectionLimit: 10,
  host: mysqlConfig.HOST,
  port: mysqlConfig.PORT,
  user: mysqlConfig.USER,
  password: mysqlConfig.PASSWORD,
  database: mysqlConfig.DATABASE
});

//创建通用查询方法, 可以promise返回
let Query = (sql, value) => {
  return new Promise((resolve, reject) => {
    // 建立连接查询
    pool.getConnection((error, connection) => {
      // 连接失败
      if(error) {
        reject({code: 0, data: error});
      }
      //通过连接查询数据库
      connection.query(sql, value, (error, results, fields) => {
        //关闭连接
        connection.release();
        //sql语句执行失败
        if(error) {
          reject({code: 0, data: error, msg: 'SQL语句执行失败!'});
        }
        //返回sql语句执行完成的结果
        resolve({code: 1, data: results, msg: 'SQL语句执行完成...'})
      })
    })
  })
};


module.exports = Query;
